package com.lanqiao.guimei.controller;

import com.lanqiao.guimei.dao.CateGoryDao;
import com.lanqiao.guimei.dao.ProductDao;
import com.lanqiao.guimei.dao.StockDao;
import com.lanqiao.guimei.dao.VendorDao;
import com.lanqiao.guimei.vo.*;
import com.lanqiao.web.mvc.annotation.Controller;
import com.lanqiao.web.mvc.annotation.RequestMapping;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Author:沈林玉
 * @date:2019/8/13 21:13
 * @Description:
 */
@Controller
public class ProductController {
    ProductDao productDao = new ProductDao();

    private static final long serialVersionUID = 1L;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    /**
     * 1.商品查询
     * @param product
     */
    @RequestMapping("/product/select")
    public String selectProduct(HttpServletRequest request, HttpSession session,Product product){
        Page<Product> productPage = (Page<Product>)session.getAttribute("productPage");
        String pageNo = request.getParameter("pageNo");

        if (productPage==null || StringUtils.isBlank(pageNo)) {
            productPage = new Page<Product>();
            productPage.setPageSize(5);
            productPage.setPageNo(1);
            productPage.setQueryObject(product);
            // 获取总记录数
            int countProduct = productDao.getCountProduct(productPage);
            productPage.setTotalRow(countProduct);
        }else{
            productPage.setPageNo(Integer.valueOf(pageNo));

        }
        session.setAttribute("productPage",productPage);

        List<Product> products = new ProductDao().selectProductByCondition(productPage);
        List<Vendor> vendorList = new VendorDao().findAll();
        List<Category> categoryList = new CateGoryDao().Categories();
        request.setAttribute("categoryList",categoryList);
        request.setAttribute("vendorList", vendorList);
        request.setAttribute("products",products);
        return "/after/product_admin.jsp";
    }

    /**
     * 按主键查询商品
     * @param product
     * @return
     */
    @RequestMapping("/product/selectById")
    public String selectProductById(HttpServletRequest request,Product product){
        String prodNo = request.getParameter("prodNo");
        product = new Product();
        product.setProdNo(prodNo);
        List<Product> products = productDao.selectProductById(product);
        if (products!=null){
            request.setAttribute("prodno",products);
            return "/after/updateProductForm.jsp";
        }
        return null;
    }

    /**
     * 按主键查询商品
     * @param product
     * @return
     */
    @RequestMapping("/product/selectSaleProd")
    public String selectSaleProd(HttpServletRequest request,Product product){
        String prodNo = request.getParameter("prodNo");
        product = new Product();
        product.setProdNo(prodNo);
        Product products = productDao.ProductById1(product);
        if (products!=null){
            request.setAttribute("prodSal",products);
            return "/after/product_sale.jsp";
        }
        return null;
    }

    /**
     * 2.新增商品
     * @param product
     * @return
     */
    @RequestMapping("/product/add")
    public String addProduct(Product product){
        boolean inserted = productDao.addProduct(product);
        if (inserted){
            return "/product/select";
        }
        return "redirect:/addProduct.jsp";
    }

    /**
     * 3.更新商品
     * @param product
     * @return
     */
    @RequestMapping("/product/doUpdate")
    public Map updateProduct(Product product){
        boolean updated = productDao.updateProduct(product);
        Map json = new HashMap();
        if (updated){
            json.put("result",true);
            return json;
        }else{
            json.put("result",false);
        }
        return json;
    }



    /**
     * 4.查询商品详情，返回商品详情+卖家ID和姓名
     * @param product
     * @param request
     */
    @RequestMapping("/product/ProductById")
    public void ProductById(Product product, HttpServletRequest request){
        Product products = new ProductDao().ProductById(product);
        request.setAttribute("products", products);
    }




    /**
     * 5.添加到购物车
     * @param product
     */
    @RequestMapping("/front/product/addToCart")
    public Map addToCart(Product product, HttpServletResponse response, HttpSession session) {
        Product products = new ProductDao().ProductById(product);

        String prodNo = products.getProdNo();
        session.setAttribute("prodNo",prodNo);
        // 从session中获取购物车
        Map<String, CartItem> cart = (Map<String, CartItem>)session.getAttribute("cart");
        Map<String, Integer> salerIdMap = (Map<String, Integer>)session.getAttribute("salerIdMap");
        // 1. 购物车不存
        if (cart == null) {
            cart = new LinkedHashMap<>();
            cart.put(product.getProdNo(), new CartItem(products, 1));

        } else {
            // 2. 购物车已存在

            // 2.1 商品已存在 购物车中
            if(cart.containsKey(product.getProdNo())){
                CartItem cartItem = cart.get(product.getProdNo());
                cartItem.setQuantity(cartItem.getQuantity() + 1);
                // 数量改变，重新放回购物车中
                cart.put(product.getProdNo(), cartItem);
            } else {
                // 2.2 商品在 购物车中 不存在
                cart.put(product.getProdNo(), new CartItem(products, 1));
            }
        }

        Integer salerId = (Integer) session.getAttribute("saler");
        if (salerIdMap == null) {
            salerIdMap = new LinkedHashMap<>();
            salerIdMap.put(product.getProdNo(),salerId);
            session.setAttribute("salerIdMap",salerIdMap);

        } else {
            Map<String, Integer> idMap = (Map<String, Integer>) session.getAttribute("salerIdMap");
            idMap.put(product.getProdNo(),salerId);
            session.setAttribute("salerIdMap",idMap);
        }
        session.setAttribute("cart", cart);

        Map json = new HashMap();
        json.put("result", true); // gson: {result: true, key2: value2, key3: value3}
        return json;
    }

    /**
     * 6.上架在线商品
     * @param saleProd
     * @return
     */
    @RequestMapping("/product/doPutaway")
    public String putawayProduct(SaleProd saleProd){
        Product product = new Product();
        product.setProdNo(saleProd.getProdNo());
        List<SaleProd> saleProdList = new ArrayList<>();
        saleProdList.add(saleProd);
        String putawayProduct = productDao.putawayProduct(product,saleProdList);
        if (putawayProduct!=null){
            return "/product/select.do";
        }else{
            return "/product/select.do";
        }
    }


    /**
     * 跳到添加商品页面
     * @param request
     * @return
     */
    @RequestMapping("/product/toAdd")
    public String toAddProduct(HttpServletRequest request){

        List<Category> categoryList = new CateGoryDao().Categories();
        request.setAttribute("categoryList",categoryList);

        List<Stock> stockList = new StockDao().findAll();
        request.setAttribute("stockList", stockList);

        List<Vendor> vendorList = new VendorDao().findAll();
        request.setAttribute("vendorList", vendorList);

        return "/after/product_add.jsp";
    }


    /**
     * 添加商品
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/product/doAdd")
    public String doAddProduct(HttpServletRequest request, HttpServletResponse response){


        response.setContentType("text/html;charset=utf-8");
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return null;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        //String uploadPath = request.getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
        //String uploadPath = "/Users/stone/Idea_workspace/beautyshop/guimei/web/after";
        String uploadPath = "E:\\蓝桥笔记和视频\\中期代码\\beautyshop\\out\\artifacts\\guimei_war_exploded\\image\\product";


        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = null;

        Product product = new Product();

        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {


                product.setProdName(formItems.get(0).getString("utf-8"));

                product.setCtgrId(Integer.valueOf(formItems.get(1).getString("utf-8")));

                product.setVenId(Integer.valueOf(formItems.get(2).getString("utf-8")));

                product.setStkId(Integer.valueOf(formItems.get(3).getString("utf-8")));

                product.setPrice(Double.valueOf(formItems.get(4).getString("utf-8")));

                product.setType(formItems.get(5).getString("utf-8"));

                product.setDescr(formItems.get(formItems.size()-1).getString("utf-8"));

                System.out.println(product);


                // 迭代表单数据
                int i = 1;
                String timeNumber = String.valueOf(new Date().getTime());
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {

                        String orgFileName = new File(item.getName()).getName();
                        //文件名后缀
                        String suffix = StringUtils.substring(orgFileName, orgFileName.lastIndexOf("."));

                        fileName = timeNumber + "_"+ i + suffix;

                        System.out.println(fileName);

                        i++;
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message",
                                "文件上传成功!");
                    } else {
                        System.out.println(item.getString("utf-8"));
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }
        product.setImage("image/product/"+fileName);

        boolean addProduct = new ProductDao().addProduct(product);

        if (addProduct) {
            // 跳转到 message.jsp
            return "/product/select.do";
        } else {
            return "redirect:/after/product_add.jsp";
        }

    }

}
